/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.core.controller;

import cn.simastudio.talos.common.constants.SimaConstants;
import cn.simastudio.talos.core.bind.annotation.CurrentUser;
import cn.simastudio.talos.core.constants.MessageCode;
import cn.simastudio.talos.core.model.base.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Usage: 获取登录表单页面、默认index
 *
 * @author Charkey
 * @date 2015/5/14 10:00
 */
@Controller
public class ShiroController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShiroController.class);

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = {"/{login:login;?.*}"})
    public String loginForm(HttpServletRequest request, ModelMap model) {

        //表示退出
        if (!StringUtils.isEmpty(request.getParameter("logout"))) {
            model.addAttribute(SimaConstants.Response.MESSAGE, messageSource.getMessage(MessageCode.USER_LOGOUT_SUCCESS, null, null));
        }

        //表示用户删除了 @see org.apache.shiro.web.filter.user.SysUserFilter
        if (!StringUtils.isEmpty(request.getParameter("notexists"))) {
            model.addAttribute(SimaConstants.Response.MESSAGE, messageSource.getMessage(MessageCode.USER_NOT_EXISTS, null, null));
        }

        //表示用户被管理员强制退出
        if (!StringUtils.isEmpty(request.getParameter("forcedlogout"))) {
            model.addAttribute(SimaConstants.Response.MESSAGE, messageSource.getMessage(MessageCode.USER_FORCED_LOGOUT, null, null));
        }

        //表示用户输入的验证码错误
        if (!StringUtils.isEmpty(request.getParameter("captchaerror"))) {
            model.addAttribute(SimaConstants.Response.MESSAGE, messageSource.getMessage(MessageCode.INVALID_CAPTCHA, null, null));
        }


        //表示用户锁定了 @see org.apache.shiro.web.filter.user.SysUserFilter
        if (!StringUtils.isEmpty(request.getParameter("blocked"))) {
            User user = (User) request.getAttribute(SimaConstants.System.CURRENT_USER);
            String reason = "这是用户被禁用的原因";
            //Todo:从数据表中获取用户被禁用的原因
            model.addAttribute(SimaConstants.Response.MESSAGE, messageSource.getMessage(MessageCode.USER_BANNED_BLOCKED, new Object[]{reason}, null));
        }

        if (!StringUtils.isEmpty(request.getParameter("unknown"))) {
            model.addAttribute(SimaConstants.Response.MESSAGE, messageSource.getMessage(MessageCode.USER_UNKNOWN_ERROR, null, null));
        }

        //登录失败了 提取错误消息
        Exception shiroLoginFailureEx =
                (Exception) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        if (shiroLoginFailureEx != null) {
            model.addAttribute(SimaConstants.Response.MESSAGE, shiroLoginFailureEx.getMessage());
        }

        //如果用户直接到登录页面 先退出一下
        //原因：isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问
        // 这样会导致登录一直死循环
        Subject subject = SecurityUtils.getSubject();
        if (subject != null && subject.isAuthenticated()) {
            subject.logout();
        }

        // Sima: 默认登录页面：web页面目录下jsp目录下的login.jsp
        return "/jsp/login.jsp";
    }

    @RequestMapping(value = {"/index"})
    public String index(@CurrentUser User user, Model model) {
        model.addAttribute(SimaConstants.System.CURRENT_USER, user);
        // Sima: 默认index页面：web页面目录下jsp目录下的index.jsp
        return "/jsp/index.jsp";
    }
}
